package xyz.kongbai121.drawingbed.utils;


import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import xyz.kongbai121.drawingbed.constant.DrawingBedConstant;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.text.SimpleDateFormat;
import java.util.Date;


/**
 * 过期图片删除工具
 */
@Component
@Slf4j
public class OverImagesDeleteUtil {

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Value("${drawing-bed.image.file-path}")
    private String filePath;

    public void imagesDelete(){
        //记录删除图片的数量
        int overNum = 0;
        while (true){
            String value = redisTemplate.opsForList().leftPop(DrawingBedConstant.OVER_IMAGES);
            if (StringUtils.isBlank(value)){
                break;
            }
            String fileUrl = filePath + value;
            File file = new File(fileUrl);
            try {
                Files.delete(file.toPath());
                overNum++;
            } catch (IOException e) {
                e.printStackTrace();
                log.error("{} 文件删除失败, 原因{}", fileUrl, e.getMessage());
            }
        }
        log.info("{}:删除了{}张图片", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()), overNum);
    }

}
